package pt.compflow;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.restlet.Component;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.Protocol;
import org.restlet.data.Status;
import org.restlet.representation.InputRepresentation;
import org.restlet.representation.Representation;

import com.hp.hpl.jena.shared.NotFoundException;

public class RequesterClientRestlet {
	
	public static Representation readStaticFile(String fileName) throws NotFoundException, IOException
	{
	    InputStream is = new FileInputStream(new File(fileName));
	    Representation representation = new InputRepresentation(is);

	    return representation;
	}
	
	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		Component component = new Component();
		component.getServers().add(Protocol.HTTP, 8081);

		
		
		
		component.getDefaultHost().attachDefault(new Restlet() {
			@Override
			public void handle(Request request, Response response) {
				final String rootPath = System.getProperty("user.dir") + "\\requester_client\\";
				String type = request.getMethod().getName();
			    String fileName = (String) request.getResourceRef().getIdentifier();
			    fileName = rootPath + fileName.substring(request.getHostRef().getHostIdentifier().length()+1);
			    System.out.println(fileName);

			    if(type.equalsIgnoreCase("get"))
			    {

			        try {
			            Representation r = readStaticFile(fileName);
			            response.setEntity(r);
			        } catch (NotFoundException e) {
			            e.printStackTrace();
			            response.setStatus(new Status(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()));
			        } catch (IOException e) {
			            e.printStackTrace();
			            response.setStatus(new Status(Status.SERVER_ERROR_INTERNAL, e.getMessage()));
			        } 
			    }
			}
		});

		component.start();

		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		boolean exit = false;
		while (!exit) {
			System.out.println("Exit? Y or N");
			String str = reader.readLine();
			if (str.compareToIgnoreCase("y") == 0)
				exit = true;
		}

		reader.close();
		component.stop();
	}
}
